package com.zjw.starter.service;

import com.zjw.model.R;
import com.zjw.model.constant.Constants;
import com.zjw.model.enums.ClientType;
import com.zjw.model.pojo.vo.MessageVO;
import com.zjw.model.pojo.vo.WsNodeInfo;
import com.zjw.starter.fegin.RemoteRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Service
public class MessageService {

    private final static Logger log = LoggerFactory.getLogger(MessageService.class);

    private RestTemplate restTemplate;
    private static final String URL_PREFIX = "http://";

    @Resource
    private RemoteRegisterService remoteRegisterService;

    public MessageService() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);// 设置连接超时，单位毫秒
        requestFactory.setReadTimeout(30000);  //设置读取超时
        restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
    }

    /**
     * 发送消息用户所有客户端
     *
     * @param messageVO
     * @return 返回发送失败的节点和客户端信息
     */
    public R<MessageVO> sendMessageToUser(MessageVO messageVO) {
        messageVO.setClientTypes(new HashSet<>());
        R<Collection<WsNodeInfo>> result = remoteRegisterService.getServersByUserId(messageVO.getGroupId(), messageVO.getTo());
        if (Constants.SUCCESS != result.getCode() || CollectionUtils.isEmpty(result.getData())) {
            return R.fail();
        }
        Collection<WsNodeInfo> nodeInfos = result.getData();
        if (CollectionUtils.isEmpty(nodeInfos)) {
            return R.fail();
        }
        Set<String> urls = new HashSet<>();
        for (WsNodeInfo nodeInfo : nodeInfos) {
            String url = URL_PREFIX + nodeInfo.getIp() + ":" + nodeInfo.getPort() + "/server/sendMessageToUser";
            if (!urls.add(url)) {
                continue;
            }
            R<Set<ClientType>> msgRes = restTemplate.postForObject(url, messageVO, R.class);
            if (Constants.SUCCESS == msgRes.getCode()) {
                continue;
            }
            messageVO.getClientTypes().addAll(msgRes.getData());
        }
        if (!CollectionUtils.isEmpty(messageVO.getClientTypes())) {
            return R.fail(messageVO);
        }
        return R.ok();
    }

    /**
     * 发送消息给用户指定客户端
     *
     * @param messageVO
     * @return
     */
    public R<Void> sendMessageToClientType(MessageVO messageVO) {
        if (CollectionUtils.isEmpty(messageVO.getClientTypes()) || messageVO.getClientTypes().size() > 1) {
            return R.fail();
        }
        ClientType clientType = messageVO.getClientTypes().iterator().next();
        R<WsNodeInfo> result = remoteRegisterService.getServerByClientType(messageVO.getGroupId(), messageVO.getTo(), clientType);
        WsNodeInfo nodeInfo = result.getData();
        if (nodeInfo == null) {
            return R.fail();
        }
        String url = URL_PREFIX + nodeInfo.getIp() + ":" + nodeInfo.getPort() + "/server/sendMessageToClientType";
        R<Set<ClientType>> msgRes = restTemplate.postForObject(url, messageVO, R.class);
        if (Constants.SUCCESS == msgRes.getCode()) {
            return R.ok();
        }
        return R.fail();
    }
}
